package com.wh.web.util.req;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.PageContext;

import com.wh.web.util.lang.StringUtil;

import sun.swing.StringUIClientPropertyKey;

public final class RequestUtil {
	public static String getParameter(HttpServletRequest request, String param) {
		String v = request.getParameter(param);
		return v == null ? "" : v;
	}

	public static int getAttribute(JspContext ctx, Object key, int defaultV) {
		Integer i = getAttribute(ctx, key);
		return (i == null) ? defaultV : i;
	}
	public static String getAttribute(JspContext ctx, Object key, String defaultV) {
		String s = getAttribute(ctx, key);
		return (s == null) ? defaultV : s;
	}
	@SuppressWarnings("unchecked")
	public static <T> T getAttribute(JspContext ctx, Object key) {
		if (key == null) return null;
		if (ctx == null) return null;
		String skey = key.toString();
		Object o = ctx.getAttribute(skey);
		if (o != null) return (T) o;
		if (ctx instanceof PageContext) {
			ServletRequest req = ((PageContext) ctx).getRequest();
			if (req != null) {
				o = req.getAttribute(skey);
				if (o != null) return (T) o;
				if (req instanceof HttpServletRequest) {
					HttpSession session = ((HttpServletRequest) req).getSession();
					if (session != null) {
						o = session.getAttribute(skey);
						if (o != null) return (T) o;
						if (session.getServletContext() != null) {
							o = session.getServletContext().getAttribute(skey);
							if (o != null) return (T) o;
						}
					}
				}
			}
		}
		return null;
	}
}